import sys
import pexpect
from model.ServerConfig import ServerModel
from model.ServerConfig import *
from sys_config_reader import SysConfigReader

# setting-item
RESET_SERVER_CONFIG= "RESET_SERVER_CONFIG"
RESET_ENCRYPT="RESET_ENCRYPT"

class ServerHandler(object):

    def __init__(self,sys_reader:SysConfigReader) -> None:
        self.sys_reader = sys_reader
        pass

    def handler(self,server:ServerModel):
        menu_type = server.menu_type;
        if(menu_type == SERVER):
            ssh = SSH(server)
            ssh.connection()

        elif(menu_type == SETTING):
            setting = Setting(server=server,sys_reader=self.sys_reader)
            setting.connection()


class Setting(object):

    item = ""
    remark=""

    def __init__(self,server:ServerModel,sys_reader:SysConfigReader) -> None:
        self.item = server.item
        self.remark = server.remark
        self.sys_reader = sys_reader

    def connection(self):
        if(self.item == RESET_SERVER_CONFIG):
            self.sys_reader.rest_server_config()
            pass
        elif(self.item == RESET_ENCRYPT):
            pass
    
class SSH(object):
    """链接服务器对象"""
    user=""
    ip=""
    password=""
    loginCmd = []

    def __init__(self,server:ServerModel) -> None:
        self.user = server.user;
        self.ip = server.inIp;
        self.password = server.password;
        self.loginCmd = server.loginCmd;
        pass

    def connection(self):
        """发起链接服务器"""
        ssh = pexpect.spawn('ssh %s@%s' % (self.user,self.ip))
        try:
            ssh.expect("password",timeout=5)
        except pexpect.exceptions.TIMEOUT:
            print('\033[1;31m' + '\t error:连接服务器超时:'+self.ip+ '\033[0m')
            return
        ssh.sendline(self.password)

        # 执行登陆后脚本命令
        if(self.loginCmd):
            for cmd in self.loginCmd:
                # 等待终端shell提示符出现
                ssh.expect(cmd["expect"],timeout=5)
                ssh.sendline(cmd["send"])
        ssh.interact()

class UserAction(object):

    def __init__(self,menu) -> None:
        self.menu = menu
        pass

    menu = None
	# 当前用户选择的环境
    env = "";

	# 当前用户所在菜单层级(1:环境列表，2:服务列表)
    level = 0;

    # 当前输入
    input_num = 0

	# 是否还未登陆，当用户登陆ssh后,再退出登陆时，会更新此状态。防止再次登陆
    notLogin = True;

    start = True

    def __receiveInputCheck(self, message:str):
        """接收用户输入结果，并校验"""
        num = input(message+":")
        if num == "":
            sys.exit(0);
        return num;

    def inputZeroHandler(self):
        """ 对用户输入0的处理 """
        if(int(self.input_num) == 0):
            if(self.level == 1):
                # 退出程序
                self.start = False
                sys.exit(0);
            if(self.level == 2):
                # 返回上级菜单
                self.level = 1
                self.inputShowMenu()
    
    def inputShowMenu(self):
        """根据输入进入的层级展示菜单"""
        if(self.level == 1):
            self.menu.showEnvList();
            self.input_num  = self.__receiveInputCheck("please input env num");
            self.env = self.menu.getEnvByNum(int(self.input_num));
        if(self.level == 2):
            self.menu.showServerList(self.env);
            self.input_num  = self.__receiveInputCheck("please input env num");


    def envChoose(self):
        """ 选择环境 """
        self.level = 1;
        self.inputShowMenu()
        
    def serverChoose(self)-> ServerModel:
        """ 选择服务器 """
        self.level = 2;
        self.inputShowMenu()

        if(int(self.input_num) == 0):
            # 在服务器菜单层级，选择0,重置为1
            self.level = 1
            return None
        
        try:
            return self.menu.server_config_list[int(self.input_num)-1];
        except IndexError:
            print('\033[93m' + '\twarn:无效的序列编号' + '\033[0m')
            return None